//
//  WJPresentationController.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/28.
//

import UIKit

import UIKit

class WJPresentationController: UIPresentationController {
    
    // 背景遮罩视图
    private lazy var dimmingView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.0, alpha: 0.5)
        view.alpha = 0.0
        // 添加点击背景消失的手势
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleDimmingViewTap))
        view.addGestureRecognizer(tapGesture)
        return view
    }()
    
    // 点击背景消失
    @objc private func handleDimmingViewTap() {
        presentingViewController.dismiss(animated: true, completion: nil)
    }
    
    // 呈现过渡将要开始时的设置
    override func presentationTransitionWillBegin() {
        guard let containerView = containerView else { return }
        
        // 添加背景遮罩
        dimmingView.frame = containerView.bounds
        containerView.insertSubview(dimmingView, at: 0)
        
        // 执行背景遮罩的淡入动画
        presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] _ in
            self?.dimmingView.alpha = 1.0
        })
    }
    
    // 呈现过渡将要结束时的工作
    override func dismissalTransitionWillBegin() {
        // 执行背景遮罩的淡出动画
        presentedViewController.transitionCoordinator?.animate(alongsideTransition: { [weak self] _ in
            self?.dimmingView.alpha = 0.0
        })
    }
    
    // 定义被呈现视图的最终位置和大小（居中显示）
    override var frameOfPresentedViewInContainerView: CGRect {
        guard let containerView = containerView else { return .zero }
        
        return containerView.bounds
    }
    
    // 容器视图布局发生变化时调用（如设备旋转）
    override func containerViewWillLayoutSubviews() {
        super.containerViewWillLayoutSubviews()
        dimmingView.frame = containerView?.bounds ?? .zero
        presentedView?.frame = frameOfPresentedViewInContainerView
    }
    
    // 消失过渡完成后的清理工作
    override func dismissalTransitionDidEnd(_ completed: Bool) {
        if completed {
            dimmingView.removeFromSuperview()
        }
    }
}
